function distance_traveled = NXTMoveLimited(distance)
power = 75;
frictionFactor = 1.1;
%Gets around tacholimit=0 motors running indefinitely issue.
if distance == 0
    distance_traveled = 0;
    return
end

% COM_CloseNXT all
% h = COM_OpenNXT();
% COM_SetDefaultNXT(h);
OpenUltrasonic(SENSOR_1);
if distance < 0
    distance = -distance;
    power = -power;
end
tacholimit = round(distance*360/(4.4*pi)*frictionFactor);
mA = NXTMotor('A', 'Power', power, 'TachoLimit',tacholimit);
mB = NXTMotor('C', 'Power', power, 'TachoLimit',tacholimit);
mA.SendToNXT();
mB.SendToNXT();
pulse = GetUltrasonic(SENSOR_1);
Z = mA.ReadFromNXT.TachoCount;
Z2 = 100;
buffer = 0;
while pulse > 8 & (((Z == 0) | (Z2 == 0)) | (Z ~= Z2))
    pulse = GetUltrasonic(SENSOR_1);
    if pulse <= 8
        buffer = 1;
    end
    Z2 = Z;
    Z = mA.ReadFromNXT.TachoCount;
end
mA.Stop('brake')
mB.Stop('brake')
distance_traveled = round(mA.ReadFromNXT.TachoCount*(4.4*pi)/360);

% Optional
% if buffer == 0
%     [theta,distance2] = NXTScan();
%     buffer = sum(distance2 < 8) > 0;
% end
if buffer == 1
    distanceReturned = NXTMove(-10);
    distance_traveled = distance_traveled-distanceReturned;
elseif abs(Z - tacholimit)/tacholimit > 0.1
    NXTMove(-10);
    distance_traveled = distance_traveled-10;
end